package com.bangdao.juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chen
 * @create 2021-01-02
 */


/**
 * 可重入锁
 */
public class ReentrantLockDemo {
    public static void main(String[] args) {
        SaleTick tick = new SaleTick();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                tick.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                tick.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                tick.sale();
            }
        }, "C").start();


    }
}

class SaleTick {
    private Integer number = 20;
    private ReentrantLock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        if (number <= 0) {
            System.out.println("票已售完！");
            //有rerun都需要解锁
            lock.unlock();
            return;
        }
        try {
            Thread.sleep(200);
            number--;
            System.out.println("买票成功,当前剩余：" + number + "张");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}